package com.nebula.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.nebula.common.Const;
import com.nebula.common.ServerResponse;
import com.nebula.pojo.Folders;
import com.nebula.pojo.UrlShare;
import com.nebula.pojo.User;
import com.nebula.service.IFileAndFolderListService;
import com.nebula.service.IFileAndFolderShareService;
import com.nebula.service.IFileService;
import com.nebula.service.IFolderService;
import com.nebula.vo.FileAndFolderListVo;
import com.nebula.vo.UrlShareListVo;

@Controller
@RequestMapping("/share")
public class FileAndFolderShareController {
	@Autowired
	private IFileAndFolderShareService fileAndFolderShareService;
	@Autowired
	private IFileAndFolderListService fileAndFolderListService;
	@Autowired
	private IFolderService folderService;
	@Autowired
	private IFileService fileService;
	
	@RequestMapping(value = "/getURLAndKey",method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse getShareURLAndKey(HttpSession session,@RequestParam("valArr")String valArr,
			@RequestParam("title")String title,
			@RequestParam("failtime") String failtime,
			@RequestParam("type") String type){
		User user = (User)session.getAttribute(Const.USERINFO);
		String str[] = valArr.split(",");
		if(str.length == 0){
			return ServerResponse.createByErrorMessage("创建私密链接失败");
		}
		return fileAndFolderShareService.getShareURLAndKey(valArr,user.getUsername(),title,failtime,type);
	}
	
	@RequestMapping(value = "/init" , method = RequestMethod.GET)
	public ModelAndView initURL(HttpSession session,HttpServletResponse response,@RequestParam("surl") String surl){
		ModelAndView modelAndView = new ModelAndView();
		User user = (User)session.getAttribute(Const.USERINFO);
		ServerResponse responseServer = fileAndFolderShareService.getInitInfo(surl);
		if(responseServer.isSuccess()){
			UrlShare urlShare = (UrlShare)responseServer.getData();
			
			String []str = urlShare.getFileIdGroup().split(",");
			int fileCount = 0 , folderCount = 0 , allFolder = 0 , allFile = 0;
			boolean isDelete = false;
			
			for(int i = 0,len = str.length;i < len;i++){
				if(str[i].length() <= 11){
					allFolder += 1;
					folderCount = folderService.getFolderCount(Integer.parseInt(str[i]));
					if(folderCount == 0) break;
				}else if(str[i].length() == 15){
					allFile += 1;
					fileCount = fileService.getFileCount(Long.parseLong(str[i]));
					if(fileCount == 0) break;
				}
			}
			
			if(allFolder > 0 && allFile > 0){
				if(fileCount == 0 || folderCount == 0) isDelete = true;
			}else if(allFolder > 0 && allFile == 0){
				if(folderCount == 0) isDelete = true;
			}else if(allFolder == 0 && allFile > 0){
				if(fileCount == 0) isDelete = true;
			}
			
			if(isDelete){
				modelAndView.setViewName("500");
			}else{
				if(Const.FAILURE.equals(urlShare.getFailureTime())){
					modelAndView.setViewName("overdue");
				}else{
					if(user.getUsername().equals(urlShare.getUsername())){
						modelAndView.addObject("surl",urlShare.getShortUrl());
						modelAndView.setViewName("redirect:/share/share_list.action");
					}else if("public".equals(urlShare.getType())){
						modelAndView.addObject("surl",urlShare.getShortUrl());
						Date date = new Date();
						date.setTime(date.getTime() + 1800 * 1000);
						Cookie cookie = new Cookie("isPublic","true");
						cookie.setPath("/");
						response.addCookie(cookie);
						modelAndView.setViewName("redirect:/share/share_list.action");
					}else{
						modelAndView.setViewName("init");
						modelAndView.addObject("username", urlShare.getUsername());
					}
				}
			}
		}else{
			modelAndView.setViewName("404");
		}
		return modelAndView;
	}
	
	@RequestMapping(value = "/share_list")
	public ModelAndView getShareList(HttpSession session,@RequestParam("surl")String surl
			,@RequestParam(value="parentId" , required = false) String parentId
			,HttpServletResponse response){
		ModelAndView modelAndView = new ModelAndView();
		
		User user = (User)session.getAttribute(Const.USERINFO);
		ServerResponse responseServer = fileAndFolderShareService.getInitInfo(surl);
		if(responseServer.isSuccess()){
			UrlShare urlShare = (UrlShare) responseServer.getData();
			
			String []str = urlShare.getFileIdGroup().split(",");
			int fileCount = 0 , folderCount = 0 , allFolder = 0 , allFile = 0;
			boolean isDelete = false;
			
			for(int i = 0,len = str.length;i < len;i++){
				if(str[i].length() <= 11){
					allFolder += 1;
					folderCount = folderService.getFolderCount(Integer.parseInt(str[i]));
					if(folderCount == 0) break;
				}else if(str[i].length() == 15){
					allFile += 1;
					fileCount = fileService.getFileCount(Long.parseLong(str[i]));
					if(fileCount == 0) break;
				}
			}
			
			if(allFolder > 0 && allFile > 0){
				if(fileCount == 0 || folderCount == 0) isDelete = true;
			}else if(allFolder > 0 && allFile == 0){
				if(folderCount == 0) isDelete = true;
			}else if(allFolder == 0 && allFile > 0){
				if(fileCount == 0) isDelete = true;
			}
			
			if(isDelete){
				modelAndView.setViewName("500");
			}else {
				if(Const.FAILURE.equals(urlShare.getFailureTime())){
					modelAndView.setViewName("overdue");
				}else{
					UrlShareListVo urlShareListVo = fileAndFolderShareService.getUrlShareInfo(urlShare);
					
					if(urlShare.getUsername().equals(user.getUsername())){
						Cookie cookie = new Cookie("isSharer", "true");
						cookie.setPath("/");
						response.addCookie(cookie);
					}else{
						Cookie cookie = new Cookie("isSharer", "");
						cookie.setPath("/");
						cookie.setMaxAge(0);
						response.addCookie(cookie);
					}
					
					List<FileAndFolderListVo> list = Lists.newArrayList();
					if(parentId == null){
						list = fileAndFolderListService.getUrlShareList(urlShareListVo.getFileIdGroup());
					}else{
						list = fileAndFolderListService.getUrlShareListByParentId(parentId,urlShareListVo.getUsername());
						Folders folders = folderService.getFolderNameByFolderId(Integer.parseInt(parentId));
						modelAndView.addObject("folderName",folders.getFolderName());
					}
					modelAndView.addObject("list",list);
					modelAndView.addObject("urlShareListVo",urlShareListVo);
					modelAndView.setViewName("share");
				}
			}
		}else{
			modelAndView.setViewName("404");
		}
		
		return modelAndView;
	}
	
	@RequestMapping(value = "/checkKey",method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse<String> checkKey(@RequestParam("key") String key,@RequestParam("surl") String surl){
		ServerResponse responseServer = fileAndFolderShareService.getInitInfo(surl);
		if(responseServer.isSuccess()){
			UrlShare urlShare = (UrlShare) responseServer.getData();
			if(key.equals(urlShare.getFileKey())){
				return ServerResponse.createBySuccessMessage("密码正确");
			}
		}
		return ServerResponse.createByErrorMessage("密码错误");
	}
	
	@RequestMapping(value = "/cancelShare",method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse<String> cancelShare(@RequestParam(value = "surl") String surl){
		return fileAndFolderShareService.cancelShare(surl);
	}
	
	@RequestMapping(value = "/cancelShareByIdGroup",method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse<String> cancelShareByIdGroup(@RequestParam(value = "groupId") String groupId){
		return fileAndFolderShareService.cancelShareByIdGroup(groupId);
	}
	
	@RequestMapping(value = "/updateSaveTimes",method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse<String> updateSaveTimes(@RequestParam("surl") String surl){
		return fileAndFolderShareService.updateSaveTimes(surl);
	}
	
	@RequestMapping(value = "/updateDownloads",method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse<String> updateDownloads(@RequestParam("surl") String surl){
		return fileAndFolderShareService.updateDownloads(surl);
	}
	
	@RequestMapping("/private")
	public String UrlShare(HttpSession session,HttpServletRequest request){
		User user = (User) session.getAttribute(Const.USERINFO);
		ServerResponse<List<UrlShareListVo>> responseServer = fileAndFolderShareService.privateShareInfo(user.getUsername());
		if(responseServer.isSuccess()){
			List<UrlShareListVo> list = (List<UrlShareListVo>) responseServer.getData();
			request.setAttribute("list", list);
		}
		return "url-share";
	}
	
	@RequestMapping("/public")
	public String publicShare(HttpServletRequest request,
			@RequestParam(value = "pageNum",defaultValue = Const.DefaultPage.pageNum)int pageNum,
			@RequestParam(value = "pageSize",defaultValue = Const.DefaultPage.pageSize)int pageSize){
		ServerResponse<List<UrlShareListVo>> responseServer = 
				fileAndFolderShareService.publicShareInfo(pageNum,pageSize,request);
		if(responseServer.isSuccess()){
			List<UrlShareListVo> list = (List<UrlShareListVo>) responseServer.getData();
			request.setAttribute("list", list);
		}
		return "public-share";
	}
	
	@RequestMapping("/search")
	public String searchPublicShare(HttpServletRequest request,
			@RequestParam(value = "pageNum",defaultValue = Const.DefaultPage.pageNum)int pageNum,
			@RequestParam(value = "pageSize",defaultValue = Const.DefaultPage.pageSize)int pageSize,
			@RequestParam(value = "queries")String queries){
		ServerResponse<List<UrlShareListVo>> responseServer = 
				fileAndFolderShareService.searchPublicShareInfo(pageNum, pageSize,queries, request);
		if(responseServer.isSuccess()){
			List<UrlShareListVo> list = (List<UrlShareListVo>) responseServer.getData();
			request.setAttribute("list", list);
			request.setAttribute("queries", queries);
		}
		return "public-share-search";
	}
}
